<?php


namespace app\admin\controller;

use think\Db;


class Store extends Base
{
    public function index()
    {
        $data = Db::name('store')
            ->order('create_time desc')
            ->field('id, name, img as img_url, create_time')
            ->paginate(config('paginate.list_rows'), false, ['query' => get_query()]);

        $show = $data->render();

        $this->assign('data', $data);
        $this->assign('page', $show);

        if (request()->isAjax()) {
            return $this->fetch('ajax_index');
        } else {
            return $this->fetch();
        }
    }

    public function add()
    {
        return $this->fetch();
    }

    public function doAdd()
    {
        $data = [];
        $data['name'] = input('name');
        $data['create_time'] = time();
        $data['img'] = input('picture');

        if(!$data['img']){
            $this->error('请添加图片');
        }
        $info = Db::name('store')->insert($data);

        if($info){
            $this->success('添加成功！', url('admin/Store/index'));
        }else{
            $this->error('添加失败,请重试');
        }
    }

    public function edit()
    {
        $id = input('id');
        $info = Db::name('store')->where('id',$id)
            ->field('id, name, img as img_url')
            ->find();

        $this->assign('info', $info);

        return $this->fetch();
    }

    public function doEdit()
    {
        $data = [];
        $data['id'] = input('id');
        $data['name'] = input('name');
        $data['img'] = input('picture');

        if(!$data['img']){
            $this->error('请添加图片');
        }
        $info = Db::name('store')->update($data);

        if($info !== false){
            $this->success('修改成功！', url('admin/Store/index'));
        }else{
            $this->error('添加失败,请重试');
        }
    }

    public function del()
    {
        $id = input('id');
        $info = Db::name('store')->where('id', $id)->field('img')->find();
        $path = ROOT_PATH . 'public/uploads/'.$info['img'];
        $this->delFile($path);
        $del = Db::name('store')->where('id', $id)->delete();

        if ($del) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

}